<template>
	<div class="Body">
		<div class="HouseInfoTop">
			<div class="title">
				<div class="titleLeft">
					<template v-if="HouseInfo.houseRregion">
						<h1>
							【{{HouseInfo.houseRregion.split(',')[0]}}——
							<template v-if="HouseInfo.houseRregion.split(',').length < 3">
								{{HouseInfo.houseRregion.split(',')[1]}}】
							</template>
							<template v-else>
								{{HouseInfo.houseRregion.split(',')[2]}}】
							</template>
							{{HouseInfo.houseName}}
						</h1>
					</template>
					<div class="msshow-weizhi">地址：{{HouseInfo.districtAddress}}</div>
				</div>
				<div class="titleRight">
					<div class="tendency" @click="addCollectHouse(HouseInfo.houseId,HouseInfo.collectOrNot)">
						<img :src="HouseInfo.collectOrNot === true ? shoucang.hover : shoucang.default" alt="收藏" />
						<span :class="{ 'hover': HouseInfo.collectOrNot === true }">{{HouseInfo.collectCount}}</span>
					</div>
					<el-button type="danger" @click="handleChange">去预订</el-button>
				</div>
			</div>
			<div class="Img" v-if="HouseInfo && HouseInfo.housePicture">
				<img style="width: 480px;height: 320px;"
					:src="$store.state.imgShowRoad2 + '/file/' + HouseInfo.housePicture.split(',')[0]" />
				<div class="ImgR">
					<img v-if="HouseInfo && HouseInfo.housePicture"
						v-for="(image, index) in HouseInfo.housePicture.split(',')" :key="index"
						:src="$store.state.imgShowRoad2 + '/file/' + image" />
				</div>
			</div>
			<div class="mshsow-zs">
				<div class="mshsow-info">
					<span></span>
					<em>营业时间：
						<b>{{HouseInfo.businessTime}}</b>
					</em>
				</div>
				<div class="mshsow-info">
					<span></span>
					<em>人均消费：
						<b>￥{{HouseInfo.housePrice}}</b>
					</em>
				</div>
				<div class="mshsow-info">
					<span></span>
					<em>联系电话：
						<b>{{HouseInfo.housePhone}}</b>
					</em>
				</div>
			</div>
		</div>
		<el-card class="box-card">
			<div class="index-title">
				<h4>商家信息</h4>
				<span>Business information</span>
				<div class="w-e-text">
					<div v-html="HouseInfo.description"></div>
				</div>
			</div>
		</el-card>
		<el-card class="box-card">
			<div id="container">
			</div>
		</el-card>
		<HouseEvaluate class="box-card" :HouseInfo="HouseInfo"></HouseEvaluate>
		<el-dialog title="预定信息" :visible.sync="dialogFormVisible" width="30%" center :before-close="handleClose">
			<el-form :model="reserveForm" :rules="rules" ref="reserveForm">
				<el-form-item label="您的姓名" :label-width="formLabelWidth" prop="reserveName">
					<el-input v-model="reserveForm.reserveName" autocomplete="off" placeholder="请输入您的姓名"></el-input>
				</el-form-item>
				<el-form-item label="到店日期" :label-width="formLabelWidth" prop="arrivalTime">
					<div class="block">
						<el-date-picker v-model="reserveForm.arrivalTime" type="datetime" placeholder="选择日期时间"
							value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="离店日期" :label-width="formLabelWidth" prop="checkoutTime">
					<div class="block">
						<el-date-picker v-model="reserveForm.checkoutTime" type="datetime" placeholder="选择日期时间"
							style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss">
						</el-date-picker>
					</div>
				</el-form-item>
				<el-form-item label="游玩天数" :label-width="formLabelWidth">
					<el-input v-model="playDays" autocomplete="off" :disabled="true"></el-input>
				</el-form-item>
				<el-form-item label="人数" :label-width="formLabelWidth">
					<el-input v-model="reserveForm.peopleNum" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="手机号码" :label-width="formLabelWidth" prop="phone">
					<el-input v-model="reserveForm.phone" autocomplete="off" placeholder="请输入您的手机号码"></el-input>
				</el-form-item>
				<div class="total-price">
					<span>总价格：</span>
					<b>￥{{ reserveForm.totalPrice }}</b>
				</div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleClose">取 消</el-button>
				<el-button type="primary" @click="SubmitInfo('reserveForm')">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import houseApi from "@/api/farmHouse.js"
	import AMapLoader from "@amap/amap-jsapi-loader";
	import {
		mapState
	} from 'vuex';
	import HouseEvaluate from "../../components/foreground/HouseEvaluate.vue"
	export default {
		components: {
			HouseEvaluate
		},
		data() {
			return {
				dialogFormVisible: false,
				userInfo: {},
				HouseInfo: {},
				reserveForm: {
					reserveName: "",
					arrivalTime: "",
					checkoutTime: "",
					playDays: "",
					phone: "",
					peopleNum: "",
					totalPrice: 0
				},
				rules: {
					reserveName: [{
						required: true,
						message: '请输入您的姓名',
						trigger: 'blur'
					}],
					arrivalTime: [{
						required: true,
						message: '请选择到店时间',
						trigger: 'blur'
					}],
					checkoutTime: [{
						required: true,
						message: '请选择离店时间',
						trigger: 'blur'
					}],
					phone: [{
							required: true,
							message: '请输入您的电话号码',
							trigger: 'blur'
						},
						{
							min: 7,
							max: 11,
							message: '长度在 7到 11个字符',
							trigger: 'blur'
						}
					]
				},
				formLabelWidth: '90px',
				marker: null, // 用于存储当前的点标记
				autoComplete: null,
				placeSearch: null,
				// adddres: [],
				map: null,
				shoucang: {
					default: require('@/assets/images/shoucang.png'),
					hover: require('@/assets/images/shoucang2.png')
				},
			}
		},
		mounted() {
			const houseId = this.getId();
			console.log("获取到的ID为：", houseId);
			this.initAMap();
		},
		unmounted() {
			this.map?.destroy();
		},
		computed: {
			playDays: function() { //计算天数
				var arrivalTime = new Date(this.reserveForm.arrivalTime);
				var checkoutTime = new Date(this.reserveForm.checkoutTime);
				if (arrivalTime && checkoutTime) {
					var timeDiff = Math.abs(checkoutTime.getTime() - arrivalTime.getTime());
					var playDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
					this.reserveForm.playDays = playDays; // 将计算结果赋值给reserveForm.playDays
					return playDays;
				}
				return '';
			},
			// 计算总价格
			calculateTotalPrice() {
				// return this.playDays * this.HouseInfo.housePrice * this.reserveForm.peopleNum;
				const rawTotalPrice = this.playDays * this.HouseInfo.housePrice * this.reserveForm.peopleNum;
				// 使用 toFixed 方法保留两位小数，并将结果转换为数字
				return Number(rawTotalPrice.toFixed(2));
			},
			coordinates() {
				if (this.HouseInfo && typeof this.HouseInfo.houseLatitude === 'string' && this.HouseInfo.houseLatitude
					.trim() !== '') {
					return this.HouseInfo.houseLatitude.split(",").map(coord => parseFloat(coord));
				} else {
					return [0, 0];; // 或者根据需要返回默认值或其他逻辑
				}
			},
			...mapState(['imgShowRoad2'])
		},
		watch: {
			// 监听相关数据变化
			playDays: 'updateTotalPrice',
			'reserveForm.peopleNum': 'updateTotalPrice',
		},
		methods: {
			async HouseDetails() {
				const res = await houseApi.HouseDetails('/znFarmhouse/HouseDetails/' + this.getId());
				if (res.code === 200) {
					this.HouseInfo = res.data;
					this.initAMap();
				}
			},
			async NotLogHouseDetails() {
				const res = await houseApi.NotLogHouseDetails('/znFarmhouse/NotLogHouseDetails/' + this.getId());
				if (res.code === 200) {
					this.HouseInfo = res.data;
					this.initAMap();
				}
			},
			async SubmitReserve() {
				if (this.$store.getters.gettoken == null) {
					this.$message.warning('您还未登录！');
				} else {
					this.updateTotalPrice();
					const res = await houseApi.SubmitReserve('/znFarmhouseReserve/subReserveInfo', {
						reserveName: this.reserveForm.reserveName,
						arrivalTime: this.reserveForm.arrivalTime,
						checkoutTime: this.reserveForm.checkoutTime,
						playDays: this.reserveForm.playDays,
						phone: this.reserveForm.phone,
						houseId: this.$route.params.houseId,
						username: this.userInfo.userName,
						peopleNum: this.reserveForm.peopleNum,
						totalPrice: this.reserveForm.totalPrice
					});
					if (res.flag == true) {
						this.$message({
							message: res.msg,
							type: 'success'
						});
					} else {
						this.$message.error(res.msg);
					}
				}
			},
			async addCollectHouse(houseId,collectOrNot) {
				if (this.$store.getters.gettoken == null) {
					this.$message.warning('您还未登录！');
				} else {
					if(collectOrNot == false){
						let collectOrNotBean = {
							houseId: houseId,
							collectStatus: collectOrNot === false ? 1 : 0
						};
						const res = await houseApi.addCollectHouse("/ZnCollectHouse/addCollectHouse", collectOrNotBean);
						if (res.code == 200) {
							this.HouseDetails();
							this.$message.success("收藏成功");
						}
					}else{
						let collectOrNotBean = {
							houseId: houseId,
							collectStatus: collectOrNot === false ? 1 : 0
						};
						const res = await houseApi.addCollectHouse("/ZnCollectHouse/addCollectHouse", collectOrNotBean);
						if (res.code == 200) {
							this.HouseDetails();
							this.$message.error("取消收藏");
						}
					}
				}
			},
			getId() {
				console.log("" + this.$route.params.houseId)
				return this.$route.params.houseId;
			},
			handleChange() {
				this.dialogFormVisible = true;
			},
			SubmitInfo(reserveForm) {
				this.$refs[reserveForm].validate((valid) => {
					if (valid) {
						this.SubmitReserve();
						this.reserveForm = {}
						this.dialogFormVisible = false;
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			handleClose() {
				this.dialogFormVisible = false;
				this.reserveForm = {}
			},
			updateTotalPrice() {
				this.reserveForm.totalPrice = this.calculateTotalPrice;
			},
			initAMap() {
				AMapLoader.load({
						key: "55d56432540aab1ea784144bd82861f5", // 申请好的Web端开发者Key，首次调用 load 时必填
						version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
						plugins: ["AMap.Scale", "AMap.ToolBar", "InfoWindow",
							"AMap.AutoComplete", "AMap.PlaceSearch"
						], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
					})
					.then((AMap) => {
						this.map = new AMap.Map("container", {
							// 设置地图容器id
							viewMode: "2D", // 是否为3D地图模式
							zoom: 20, // 初始化地图级别
							center: this.coordinates,// 初始化地图中心点位置
							scrollWheel: false,// 禁用地图的鼠标滚轮缩放功能 
						});

						// 添加缩放控件
						this.map.addControl(new AMap.ToolBar({
							position: 'RT' // 'RB' 表示右下角
						}));

						// 创建地图标记
						//检查确保 this.coordinates 是一个长度为 2 的数组
						if (this.coordinates && this.coordinates.length === 2 && !isNaN(this.coordinates[0]) && !isNaN(
								this.coordinates[1])) {
							let marker = new AMap.Marker({
								position: this.coordinates,
								map: this.map,
							});
							// 创建信息窗体
							let infoWindow = new AMap.InfoWindow({
								content: this.getInfoWindowContent(),
								offset: new AMap.Pixel(0, -30), // 信息窗体位置偏移
							});

							// 直接打开信息窗体
							infoWindow.open(this.map, marker.getPosition());
							// 将地图移动到标记位置
							this.map.setCenter(this.coordinates);
						}
					})
					.catch((e) => {
						console.log(e);
					});
			},
			getInfoWindowContent() {
				if (this.HouseInfo) {
					let imagePath = '';
					if (this.HouseInfo.housePicture && typeof this.HouseInfo.housePicture === 'string') {
						imagePath = this.imgShowRoad2 + '/file/' + this.HouseInfo.housePicture.split(',')[0];
					}
					return `
			          <div style="display: flex;align-items: center;" >
						<img style="width: 200px;height: 150px;"
							src="${imagePath}" />
						<div style="margin:0 0 0 10px;">
							<p>${this.HouseInfo.houseName}</p>
							<p>电话: ${this.HouseInfo.housePhone}</p>
						</div>
			          </div>
			        `;
				} else {
					return '暂无信息'; // 如果 HouseInfo 未加载，显示暂无信息
				}
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
			if (this.$store.getters.gettoken == null) {
				this.NotLogHouseDetails()
			} else {
				this.HouseDetails();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.Body {
		margin: 0 15% 0 15%;

		.HouseInfoTop {
			padding: 10px;
			width: 96.5%;
			display: flex;
			flex-direction: column;
			background-color: #fff;
			margin: 10px 0 20px 0;

			.title {
				display: flex;
				position: relative;

				.titleLeft {
					width: 80%;
					height: 100%;

					.msshow-weizhi {
						width: 60%;
						height: 35px;
						line-height: 35px;
						float: left;
						font-size: 14px;
						color: #666;
						margin-bottom: 20px;
					}
				}
				.titleRight{
					display: flex;
					align-items: center;
					.el-button {
						margin-left: 50px;
						width: 100px;
						height: 55px;
					}
				}
				

			}

			.Img {
				display: flex;

				.ImgR {
					width: 710px;
					height: 310px;
					display: flex;
					justify-content: space-around;
					flex-wrap: wrap;
					float: right;

					img {
						width: 230px;
						height: 155px;
						margin-bottom: 10px;
					}

				}
			}

			.mshsow-zs {
				width: 50%;
				height: auto;
				margin: 20px auto;
				display: flex;
				float: left;
				justify-content: space-between;
				flex-wrap: nowrap;

				.mshsow-info {
					margin: 0;
					padding: 0;

					em {
						color: #666;
						font-size: 16px;
						line-height: 50px;
						float: left;
						margin-left: 5px;

						b {
							color: #ff9305;
							font-size: 18px;
						}
					}
				}
			}
			.tendency {
				display: flex;
				align-items: center;
				color: #909090;
			
				img {
					margin: 0;
					width: 30px;
				}
			
				span {
					font-family: PingFangSC-Regular;
					font-size: 20px;
			
				}
			}
		}

		.box-card {
			width: 98%;
			margin-bottom: 20px;

			.index-title {
				height: auto;
				margin: 40px auto;
				text-align: center;

				h4 {
					margin: 0;
					font-size: 24px;
					color: #2c92f8;
					line-height: 35px;
					height: 35px;
				}

				span {
					font-size: 12px;
					line-height: 24px;
				}

				.minsu-photo {
					width: 100%;
					height: auto;
					float: left;
					margin: 20px 0 20px 0;

					img {
						width: 280px;
						margin: 5px;
						height: 185px;
					}
				}
			}

			#container {
				padding: 0px;
				margin: 0px;
				width: 100%;
				height: 500px;
			}
		}
	}
</style>